package com.automobile.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 处理日期的多种格式
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-05 20:07
 */

public class CustomDateConverter implements Converter<String, Date> {

	private static final List<String> formarts = new ArrayList<String>();

	static {
		formarts.add("yyyy-MM");
		formarts.add("yyyy-MM-dd");
		formarts.add("yyyy-MM-dd hh:mm");
		formarts.add("yyyy-MM-dd hh:mm:ss");

		formarts.add("yyyy/MM");
		formarts.add("yyyy/MM/dd");
		formarts.add("yyyy/MM/dd hh:mm");
		formarts.add("yyyy/MM/dd hh:mm:ss");

		formarts.add("yyyy.MM");
		formarts.add("yyyy.MM.dd");
		formarts.add("yyyy.MM.dd hh:mm");
		formarts.add("yyyy.MM.dd hh:mm:ss");
	}

	@Override
	public Date convert(String source) {
		String value = (source == null) ? "" : source.trim();
		if (StringUtils.isEmpty(value)) {
			return null;
		}
		Date result = null;
		for (String format : formarts) {
			try {
				result = parseDate(value, format);
			} catch (ParseException e) {
			}
		}

		if (result == null) {
			throw new IllegalArgumentException("Invalid date value \"" + source + "\"");
		}
		return result;
	}

	private Date parseDate(String dateStr,
			String format) throws ParseException {
		DateFormat dateFormat = new SimpleDateFormat(format);
		return (Date) dateFormat.parse(dateStr);
	}

}